<template>
  <div>
    ==={{ imageSrc }}
    <el-upload
      class="avatar-uploader"
      action="#"
      :show-file-list="false"
      :before-upload="beforeAvatarUpload"
      :http-request="upload"
    >
      <img v-if="imageUrl" :src="imageUrl" class="avatar">
      <i v-else class="el-icon-plus avatar-uploader-icon" />
    </el-upload>
  </div>
</template>

<script>
export default {
  name: 'UploadsImg',
  props: {
    imageSrc: {
      type: String
    }
  },
  data() {
    return {
      imageUrl: ''
    }
  },
  //   watch: {
  //     imageSrc: {
  //       handler(newVal) {
  //         this.imageUrl = newVal
  //       },
  //       immediate: true
  //     }
  //   },
  methods: {
    // :on-success="handleAvatarSuccess"  //删除
    // handleAvatarSuccess(res, file) {
    //   this.imageUrl = URL.createObjectURL(file.raw)
    // },  //不生效
    /*
    action属于组件默认提交行为需要填写请求地址,如果不使用可以设置成# 然后使用自定义 http-request 覆盖
    使用了http-request  on-success钩子函数不会再触发

    */
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    upload({ file }) {
      //   console.log(file, 990)
      // 自定义函数可以实现图片上传
      if (file) {
        var COS = require('cos-js-sdk-v5')

        // SECRETID 和 SECRETKEY请登录 https://console.cloud.tencent.com/cam/capi 进行查看和管理
        var cos = new COS({
          SecretId: 'AKID1sTnreAOL1RaS4OSFkywd3C4fz4sQhhQ',
          SecretKey: 'UhdIgofGaeRxCArDJ9i12mGTP4SZPyHJ'
        })

        cos.putObject(
          {
            Bucket: 'web70-1309634858' /* 必须 */,
            Region: 'ap-nanjing' /* 存储桶所在地域，必须字段 */,
            Key: file.name /* 必须 */,
            StorageClass: 'STANDARD',
            Body: file, // 上传文件对象
            onProgress: function(progressData) {
              console.log(JSON.stringify(progressData))
            }
          },
          (err, data) => {
            console.log(err || data, 771)
            console.log(data.Location)
            console.log(this)
            this.imageUrl = 'https://' + data.Location // 显示图片
          }
        )
      }
    }
  }
}
</script>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
